/**
 * Created by shidaiapp on 2017/9/29.
 */

import {isEmpty} from "../../../js/commonUtils";

/**
 * 发送
 * @param self
 * @param tiyData
 */
export const init = (self, tiyData) => {
    tiyData.tData.emailDetail.title = "";
    tiyData.tData.emailDetail.content = "";
    self.receiverEmail="";
    self.fileList=[];
};

/**
 * 发送
 * @param self
 * @param tiyData
 */
export const send = (self, tiyData) => {
  let fromUser = self.$store.getters.siteEmail;
  let sendName = self.$store.getters.sendName;
  let isSend=self.isSend;
  if(self.receiveUser.length==0){
    isSend=true;
  }

  if(!isSend&&0 == self.receiveUser.length){
    self.$Message.error("收件人不能为空");
    return;
  }
  if(isSend&&isEmpty(self.receiverEmail)){
    self.$Message.error("收件人不能为空");
    return;
  }
  if(isEmpty(fromUser)){
    self.$Message.error("您的帐号还没有设置邮箱，请先联系上级管理员设置邮箱");
    return;
  }
  if(isEmpty(tiyData.tData.emailDetail.title)){
    self.$Message.error("标题不能为空");
    return;
  }
  if(isEmpty(tiyData.tData.emailDetail.content)){
    self.$Message.error("内容不能为空");
    return;
  }
  let  receiveUserList=[];
  if(isSend){
    let receiveArray=self.receiverEmail.split(",");
    for(let i=0;i<receiveArray.length;i++){
      let email=receiveArray[i];
      let one=email.indexOf('<');
      let two=email.indexOf('>');
      if(one==-1){
        let item={
          contactEmail:email,
        };
        receiveUserList.push(item);
      }else{
        let item={
          contactEmail:email.slice(one+1,two),
        };
        receiveUserList.push(item);
      }
    }
  }

  self.$Spin.show();
  self.$apiEmail.sendEmail(
    {
      receiveUser:isSend?receiveUserList:self.receiveUser,
      fromUser:fromUser,
      sendName:sendName,
      title:tiyData.tData.emailDetail.title ,
      content:createContent(self, tiyData),
      text:self.$refs.myEditor.quill.container.innerText,
      attachmentList:self.fileList
    }
    ).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.info("发送成功");
      self.sendSuccess();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
/**
 * 发送
 * @param self
 * @param tiyData
 */
export const createContent = (self, tiyData) => {
  var html =
  "<html lang=\"zh\" data-hairline=\"true\" data-theme=\"light\"><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1\"></head>"
  + "<body style=\"max-width:100%;padding: 16px\">" + tiyData.tData.emailDetail.content + "</body>"
  + "</html>";
  html = html.replace("<img","<img style=\"max-width:100%\"")
  return html;
};


